import datetime
import re

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

STATUS = (
    (0, "无"),
    (1, "打开浏览器"),
    (2, "登录"),
    (3, "登录完成"),
    (4, "选择按钮"),
    (5, "选择按钮完成"),
    (6, "选择tab"),
    (7, "选择tab完成"),
    (8, "准备创建分组"),
    (9, "开始创建分组"),
    (10, "正在创建分组"),
    (11, "等待上传"),
)


class WxUpload():
    def __init__(self):
        self.driver = webdriver.Firefox()
        self.status = 0
        self.url_dict = {}
        #
        self.open_browser()
        self.login()
        self.select_menu()
        self.select_tab()
        self.select_group()

    def open_browser(self):
        print('正在打开火狐浏览器')
        self.driver.get('https://mp.weixin.qq.com')
        self.driver.maximize_window()
        self.set_status(1)

    def login(self):
        wait_login = WebDriverWait(self.driver, 10)
        account = wait_login.until(EC.presence_of_element_located((By.NAME, 'account')))
        password = wait_login.until(EC.presence_of_element_located((By.NAME, 'password')))
        account.send_keys('1003097699@qq.com')
        password.send_keys('crit311040w')
        btn_login = wait_login.until(EC.presence_of_element_located((By.CLASS_NAME, 'btn_login')))
        btn_login.click()
        self.set_status(2)
        print('请扫描二维码确认登录！默认等待（60秒）')

    def select_menu(self):
        WebDriverWait(self.driver, 60).until(EC.visibility_of_element_located((By.ID, 'menuBar')))
        self.set_status(3)
        menu_res = None
        all_menu = self.driver.find_elements_by_class_name('js_nav_item')
        for menu in all_menu:
            if menu.get_attribute('title') == '素材管理':
                menu_res = menu
                break

        menu_res.click()
        self.set_status(4)

    def select_tab(self):
        wait_tab = WebDriverWait(self.driver, 20)
        img_tab = None
        tab_ul = wait_tab.until(EC.visibility_of_element_located((By.CLASS_NAME, 'weui-desktop-tab__navs')))
        self.set_status(5)
        tabs = tab_ul.find_elements_by_tag_name('a')
        for tab in tabs:
            if tab.text == "图片":
                img_tab = tab
                break

        img_tab.click()
        self.set_status(6)

    def select_group(self):
        cur_time = datetime.datetime.now().strftime('%Y%m')
        cur_group = self.get_group(cur_time)
        self.set_status(7)
        if cur_group is None:
            self.create_group(cur_time)
            cur_group = self.get_group(cur_time)

        if cur_group is None:
            print('分组不存在：' + cur_time)
        else:
            cur_group.click()

        cur_group_text = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'weui-desktop-img-group__name')))
        self.set_status(11)
        print('把所有图片上传到[%s]分组' % cur_time)

    def get_group(self, cur_time):
        # 展开分组
        try:
            btn_more = self.driver.find_element_by_class_name('weui-desktop-tag__more-btn')
            btn_more.click()
        except:
            print("[展开分组]按钮不存在")

        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'weui-desktop-tags')))
        groups = self.driver.find_elements_by_css_selector('.weui-desktop-tags li')
        for group in groups:
            if group.get_attribute('title') == cur_time:
                return group
        return None

    def create_group(self, cur_time):
        print('创建分组: ' + cur_time)
        self.set_status(8)
        btn_group = self.driver.find_element_by_css_selector('.weui-desktop-btn_add-img-group')
        btn_group.click()
        group_panel = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(
            (By.CSS_SELECTOR, '.weui-desktop-popver_add-img-group .weui-desktop-popover_pos-up-center')))
        self.set_status(9)
        input = self.driver.find_element_by_css_selector(
            '.weui-desktop-popver_add-img-group .weui-desktop-popover_pos-up-center .weui-desktop-form__input')
        input.send_keys(cur_time)
        btn_sure = self.driver.find_element_by_css_selector(
            '.weui-desktop-popver_add-img-group .weui-desktop-popover_pos-up-center .weui-desktop-btn_primary')
        btn_sure.click()
        self.set_status(10)

    def set_status(self, s):
        self.status = s
        print("--->当前状态：" + STATUS[self.status][1])

    def get_status(self):
        return self.status

    def get_upload_url(self):
        self.jumpTo(1)
        self.get_urls()
        btn_next = self.has_next()
        while btn_next is not None and btn_next.is_displayed():
            btn_next.click()
            self.get_urls()
            btn_next = self.has_next()
            if btn_next is None or btn_next.is_displayed() == False:
                break

        return self.url_dict

    def jumpTo(self, page):
        try:
            input = self.driver.find_element_by_class_name("weui-desktop-pagination__input")
            input.send_keys(1)
            input.send_keys(Keys.ENTER)
            print('跳转到第1页')
            WebDriverWait(self.driver, 10).until(
                EC.invisibility_of_element_located((By.CLASS_NAME, 'weui-desktop-pagination__input')))
        except:
            print('未找到跳转输入框')

    def has_next(self):
        btn_next = None
        try:
            btns = self.driver.find_elements_by_css_selector('.weui-desktop-pagination .weui-desktop-btn_mini')
            for btn in btns:
                if btn.text == '下一页':
                    btn_next = btn
                    break
        except:
            print('已经到最后一页，图片搜索完成')
        return btn_next

    def get_urls(self):
        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'weui-desktop-img-picker__list')))
        img_lis = self.driver.find_elements_by_class_name('weui-desktop-img-picker__list > li')
        for li in img_lis:
            img_name = li.find_element_by_tag_name('strong').text
            img_style = li.find_element_by_tag_name('i').get_attribute('style')
            res = re.match('.*\"(.*)\".*', img_style)
            img_url = res.group(1)
            self.url_dict[img_name] = img_url

        img_num = len(img_lis)
        if img_num > 0:
            labels = self.driver.find_elements_by_class_name('weui-desktop-pagination__num__wrp > label')
            cur_page = labels[0].text
            total_page = labels[1].text
            print('共 %s 页，正在搜索 %s 页：%d个' % (total_page, cur_page, img_num))
        else:
            print('没有找到图片')


if __name__ == '__main__':
    upload = WxUpload()
    upload.get_upload_url()
